package com.ywgt.system.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ywgt.system.pojo.AuthUser;
import com.ywgt.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CustomerUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private UserService userService;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //接收前端发送的json数据
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)||request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)){
            UsernamePasswordAuthenticationToken authRequest=null;
            try {
                //使用继承了SpringSecurityD Userdetail 的实体类接收参数
                AuthUser user = objectMapper.readValue(request.getInputStream(), AuthUser.class);
                //对用户名和密码进行校验
                if (userService.checkLogin(user.getUsername(),user.getPassword())) {
                    //生成AuthenticationToken
                    authRequest = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
                    setDetails(request,authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.attemptAuthentication(request,response);
    }
}
